/* eslint-disable vue/no-template-shadow */
<template>
  <div class="departments">
    <!-- 添加一个 el-card -->
    <el-card>
      <div class="content">
        <!-- 顶部的导航区域 -->
        <el-tabs
          v-model="activeName"
          class="mytabs"
        >
          <el-tab-pane
            label="组织架构"
            name="first"
          />
        </el-tabs>
        <!-- 组织结构区域 -->
        <div class="dept">
          <!-- 上面的头部 -->
          <treetools
            class="header"
            :is-header="true"
            :data="headerData"
            @addShow="addShow"
          />
          <!-- 下面的组织架构 -->
          <el-tree :data="data">
            <treetools
              slot-scope="{ data }"
              :is-header="false"
              :data="data"
              @getNewData="getDeptData"
              @addShow="addShow"
              @editShow="editShow"
            />
          </el-tree>
        </div>
      </div>
    </el-card>
    <!-- 弹出层 -->
    <addDept
      ref="mypanel"
      :dialog-show.sync="dialogShow"
      :current-id="currentId"
      @updateData="getDeptData"
    />
  </div>
</template>

<script>
import { getDeptApi } from '@/api/departments.js'
export default {
  components: {
    treetools: () => import('./components/tree-tools.vue'),
    addDept: () => import('./components/add-dept.vue')
  },
  data() {
    return {
      activeName: 'first',
      data: [],
      // 头部结构的数据源
      headerData: {},
      dialogShow: false,
      currentId: ''
    }
  },
  created() {
    this.getDeptData()
  },
  methods: {
    async getDeptData() {
      const { data: res } = await getDeptApi()
      this.data = this.turnData(res.data.depts, '')
      // this.data = res.data.depts
      this.headerData = res.data.depts[0]
      this.headerData.manager = '管理员'
    },
    turnData(data, pid) {
      const res = []
      data.forEach(item => {
        if (item.pid === pid) {
          const children = this.turnData(data, item.id)
          if (children.length !== 0) {
            item.children = children
          }
          res.push(item)
        }
      })
      return res
    },
    addShow(currentId) {
      this.dialogShow = true
      this.currentId = currentId
      // console.log(currentId)
    },
    editShow(currentId) {
      this.dialogShow = true
      this.$refs.mypanel.getDeptId(currentId)
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  margin: 20px;
  .mytabs {
    margin: 40px;
  }
  .dept {
    padding: 0 100px;
    .header {
      padding-bottom: 10px;
      border-bottom: 1px solid #ccc;
    }
  }
}
</style>
